#include "work_group.h"
#include "work_thread.h"
#include "event2/event.h"
#include <iostream>
#include <sstream>
#include "com/simple_logger.h"
#include "transmit/net_bus.h"

using namespace std;

WorkGroup::WorkGroup(int num)
    : num_(num)
{
    // 创建消息总线
    net_bus_ = new NetBus();
}

WorkGroup::~WorkGroup()
{
    ExitSafety();
}

bool WorkGroup::Init()
{
    // 直接初始化指定的工作线程
    for (int i = 0; i < num_; i++)
    {
        int id = group_.size() + 1;
        WorkThread *work = new WorkThread(this, id, net_bus_);
        if (!work->Init())
        {
            return false;
        }
        work->Start(); // thread start...
        group_.push_back(work);
        // 将当前初始化完成的工作线程注册进消息总线
        net_bus_->Regist(work); // regist thread to netbus
    }
    return true;
}

void WorkGroup::CreateConnection(int sock)
{
    int min = -1;
    WorkThread *work = nullptr;
    // 遍历寻找负载最轻的线程
    for (auto it = group_.begin(); it != group_.end(); it++)
    {
        if (min == -1)
        {
            min = (*it)->connect_num();
            work = (*it);
        }
        else if ((*it)->connect_num() < min)
        {
            min = (*it)->connect_num();
            work = (*it);
        }
    }
    // 添加一条socket fd进队列并通过管道激活
    work->AddSocket(sock);
    work->Notify("c");
}

void WorkGroup::ExitSafety()
{
    while (!group_.empty())
    {
        WorkThread *wt = group_.back();
        wt->Stop();
        delete wt;
        group_.pop_back();
    }
    if (net_bus_)
    {
        delete net_bus_;
    }
}